﻿using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Myotragus.Data.Containers;

namespace Myotragus.Data.Hbm
{
	public class ResolutionHbmGenerator : IResolutionHbmGenerator
	{
		public IEntitiesContainer Entities { get; private set; }

		private static readonly Regex Resolve =
			new Regex(@"\""\$Resolve\s*\:\s*(?<Type>[^\""]+)\""");

		public ResolutionHbmGenerator(IEntitiesContainer entities, ITypeFinder finder,
			ITypeNameParser parser)
		{
			Entities = entities;
			Finder = finder;
			Parser = parser;
		}

		protected ITypeNameParser Parser { get; private set; }

		protected ITypeFinder Finder { get; private set; }

		public string Generate(string hbmTemplate)
		{
			var result = new StringBuilder(hbmTemplate.Length);
			var startAt = 0;

			do
			{
				var match = Resolve.Match(hbmTemplate, startAt);

				if (!match.Success)
					break;

				var typeName = match.Groups["Type"];

				result.Append(hbmTemplate.Substring(startAt, match.Index - startAt));
				result.Append(GetResolvedTypeName(typeName.Value));

				startAt = match.Index + match.Length;
			}
			while (true);

			result.Append(hbmTemplate.Substring(startAt));

			return result.ToString();
		}

		private string GetResolvedTypeName(string typeName)
		{
			var parsed = Parser.Parse(typeName);
			var found = Finder.FindType(parsed.First(), parsed.Skip(1));

			return string.Concat("\"", Entities.ResolveType(found).ToString(), "\"");
		}
	}
}